import * as vscode from 'vscode';
import { DeepseekAPI } from './deepseekAPI';
import { getLanguageConfig, SUPPORTED_LANGUAGES } from './languageSupport';

export interface SnippetTemplate {
    prefix: string;
    description: string;
    body: string[];
    scope: string;
    variables?: { name: string; description: string }[];
}

interface Snippets {
    [key: string]: {
        prefix: string;
        description: string;
        body: string[];
        scope?: string;
    };
}

export class SnippetGenerator {
    private deepseekAPI: DeepseekAPI;

    constructor(deepseekAPI: DeepseekAPI) {
        this.deepseekAPI = deepseekAPI;
    }

    public async generateSnippet(
        description: string,
        language: string,
        context?: string
    ): Promise<SnippetTemplate> {
        try {
            const response = await this.deepseekAPI.generateCodeSnippet(description, language, context);
            return this.parseSnippetResponse(response, language);
        } catch (error) {
            console.error('Snippet generation error:', error);
            throw new Error('代码片段生成失败，请重试');
        }
    }

    private parseSnippetResponse(response: any, language: string): SnippetTemplate {
        try {
            if (response.choices[0].function_call) {
                // 解析 Function Calling 响应
                const args = JSON.parse(response.choices[0].function_call.arguments);
                return {
                    prefix: args.prefix,
                    description: args.description,
                    body: args.body,
                    scope: language,
                    variables: args.variables || []
                };
            } else {
                // 降级处理
                const content = response.choices[0].message.content;
                const parsed = JSON.parse(content);
                return {
                    prefix: parsed.prefix,
                    description: parsed.description,
                    body: Array.isArray(parsed.body) ? parsed.body : [parsed.body],
                    scope: language
                };
            }
        } catch (error) {
            console.warn('Error parsing snippet response:', error);
            return {
                prefix: 'custom',
                description: 'Custom generated snippet',
                body: response.choices[0].message.content.split('\n'),
                scope: language
            };
        }
    }

    public async saveSnippet(snippet: SnippetTemplate): Promise<void> {
        const config = getLanguageConfig(snippet.scope);
        if (!config) {
            throw new Error(`Unsupported language: ${snippet.scope}`);
        }

        const snippetPath = this.getSnippetFilePath(config.id);
        let snippets: Snippets = {};

        try {
            const existing = await vscode.workspace.fs.readFile(vscode.Uri.file(snippetPath));
            snippets = JSON.parse(existing.toString());
        } catch (error) {
            // 文件不存在，使用空对象
        }

        // 添加变量说明到描述中
        if (snippet.variables && snippet.variables.length > 0) {
            snippet.description += '\n\n变量说明:\n' + 
                snippet.variables.map(v => `${v.name}: ${v.description}`).join('\n');
        }

        snippets[snippet.prefix] = {
            prefix: snippet.prefix,
            description: snippet.description,
            body: snippet.body,
            scope: snippet.scope
        };

        await vscode.workspace.fs.writeFile(
            vscode.Uri.file(snippetPath),
            Buffer.from(JSON.stringify(snippets, null, 2))
        );
    }

    private getSnippetFilePath(languageId: string): string {
        const snippetsPath = vscode.Uri.joinPath(
            vscode.workspace.workspaceFolders?.[0]?.uri || vscode.Uri.file(''),
            '.vscode',
            `${languageId}.code-snippets`
        ).fsPath;
        return snippetsPath;
    }
} 